package com.tsingteng.cosfun.ui.cosfun.adapter;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.bean.CommBean;
import com.tsingteng.cosfun.utils.DataUtil;
import com.tsingteng.cosfun.utils.DateUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.MyClickableSpan;
import com.tsingteng.cosfun.utils.StringUtils;
import com.umeng.commonsdk.debug.E;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.hdodenhof.circleimageview.CircleImageView;

public class CommListAdapter extends RecyclerView.Adapter {
    public enum FooterState {
        Normal, Loading, TheEnd;
    }

    private final int FOOTERLAYOUT = 100;//加载更多
    Context context;
    public FooterHolder mFooterHolder;
    List<CommBean.CommData> commList = null;
    OnItemClickListener onItemClickListener = null;
    private long authorId;
    public static Map<String, String> txtIdMap = null;

    public CommListAdapter(Context context, List<CommBean.CommData> commList, OnItemClickListener onItemClickListener) {
        this.context = context;
        this.commList = commList;
        this.onItemClickListener = onItemClickListener;
        txtIdMap = new HashMap<String, String>();
    }
    public void setAuthorId(long authorId){
        this.authorId = authorId;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        if (viewType == 0) {
            view = LayoutInflater.from(context).inflate(R.layout.fragment_comment_dialog_item, parent, false);
            return new CommHolder(view);
        } else {//加载更多
            view = LayoutInflater.from(context).inflate(R.layout.listview_footer, parent, false);
            mFooterHolder = new FooterHolder(view);
            return mFooterHolder;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof CommListAdapter.CommHolder) {
            ((CommListAdapter.CommHolder) holder).setData(position);
        }
    }

    @Override
    public int getItemCount() {
        if (commList == null) {
            return 0;
        }
        return commList.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (getItemCount() > 0 && position == getItemCount() - 1) {
            return FOOTERLAYOUT;
        } else {
            return 0;
        }
    }

    //icon
    class CommHolder extends RecyclerView.ViewHolder {
        CircleImageView circleImageView = null;
        CircleImageView answerItemImg;
        TextView author_tv;
        TextView zan_tv;
        LinearLayout item_lin;
        TextView author_comment_tv;
        LinearLayout answer_comment_lin;
        TextView answer_author_tv;
        TextView answer_author_comment_tv;
        TextView item_time_tv;
        TextView author_tv_des;
        RelativeLayout rel;
        private final ImageView mIvGreat;

        public CommHolder(View itemView) {
            super(itemView);
            circleImageView = itemView.findViewById(R.id.comm_item_img);
            answerItemImg = itemView.findViewById(R.id.answer_item_img);
            author_tv = itemView.findViewById(R.id.comm_item_author);
            author_tv_des = itemView.findViewById(R.id.comm_item_author_des);
            zan_tv = itemView.findViewById(R.id.comm_item_zan);
            item_lin = itemView.findViewById(R.id.comm_item_lin);
            mIvGreat = itemView.findViewById(R.id.iv_great);
            author_comment_tv = itemView.findViewById(R.id.comm_item_author_comment);
            answer_comment_lin = itemView.findViewById(R.id.comm_item_answer_comment_lin);
            answer_author_tv = itemView.findViewById(R.id.comm_item_answer_author);
            answer_author_comment_tv = itemView.findViewById(R.id.comm_item_answer_author_comment);
            item_time_tv = itemView.findViewById(R.id.comm_item_time);
            rel = itemView.findViewById(R.id.comm_item_parent);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void setData(int position) {
            CommBean.CommData commData = commList.get(position);
            if (commData.getCommentUserShot() != null)
//                Glide.with(context).load(commData.getCommentUserShot()).into(circleImageView);
            ImageUtils.LoadImage(context,commData.getCommentUserShot(),circleImageView);
            author_tv.setText(commData.getCommentUserName());
            item_time_tv.setText(DateUtils.getCommShowTime(commData.getCommentTime()));

            String r = matchReplaceTxt(commData.getCommentText());
            SpannableString msp = getWeiBoContent(context, r, author_comment_tv);
            author_comment_tv.setText(msp);
            if (commList.get(position).getCommentUserId() == authorId){
                author_tv_des.setVisibility(View.VISIBLE);
            }else{
                author_tv_des.setVisibility(View.GONE);
            }
            if (commData.getParentCommentUserName() != null) {
                answer_comment_lin.setVisibility(View.VISIBLE);
                ImageUtils.LoadImage(context,commData.getParentCommentUserShot(),circleImageView);
                answer_author_tv.setText(commData.getParentCommentUserName());
                r = matchReplaceTxt(commData.getParentCommentText());
                msp = getWeiBoContent(context, r, answer_author_comment_tv);
                answer_author_comment_tv.setText(msp);
            } else {
                answer_comment_lin.setVisibility(View.GONE);
            }
            if (commData.getIslike() == 1) {
                mIvGreat.setImageDrawable(context.getResources().getDrawable(R.drawable.great_pink_icon));
            } else {
                mIvGreat.setImageDrawable(context.getResources().getDrawable(R.drawable.great_icon));
            }


            zan_tv.setText(StringUtils.formatZanCount(commData.getLikeTimes()) + "");
            rel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemClick(position, commData.getCommentId());
                    }
                }
            });
            mIvGreat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        if (commData.getIslike() == 1) {
                            onItemClickListener.onLikeClick(position, commData.getCommentId(), "0");
                        } else {
                            onItemClickListener.onLikeClick(position, commData.getCommentId(), "1");
                        }

                    }
                }
            });
        }


    }

    public class FooterHolder extends RecyclerView.ViewHolder {
        View mLoadingViewstubstub;
        View mEndViewstub;
        public CommListAdapter.FooterState status = CommListAdapter.FooterState.Normal;

        public FooterHolder(View itemView) {
            super(itemView);
            mLoadingViewstubstub = itemView.findViewById(R.id.glistview_footer_content_rel);
            mEndViewstub = itemView.findViewById(R.id.glistview_footer_nomore_rel);
        }

        //根据传过来的status控制哪个状态可见
        public void setStatus(CommListAdapter.FooterState status) {
            this.status = status;
            switch (status) {
                case Normal:
                    setAllGone();
                    break;
                case Loading:
                    setAllGone();
                    mLoadingViewstubstub.setVisibility(View.VISIBLE);
                    break;
                case TheEnd:
                    setAllGone();
                    mEndViewstub.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }

        }

        //全部不可见
        void setAllGone() {
            if (mLoadingViewstubstub != null) {
                mLoadingViewstubstub.setVisibility(View.GONE);
            }
            if (mEndViewstub != null) {
                mEndViewstub.setVisibility(View.GONE);
            }
        }

    }

    public interface OnItemClickListener {
        void onItemClick(int position, String commId);

        void onLikeClick(int position, String commId, String type);

        void onUserClick(String userId);
    }

    /**
     * 设置微博内容样式
     *
     * @param context
     * @param source
     * @param textView
     * @return
     */
    private SpannableString getWeiBoContent(final Context context, String source, TextView textView) {
        SpannableString spannableString = new SpannableString(source);
        String s = "@[\u4e00-\u9fa5\\w]+";
        s = "@(.*?)\\s";
        Pattern pattern = Pattern.compile(s);
        Matcher matcher = pattern.matcher(spannableString);
        if (matcher.find()) {
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            matcher.reset();
        }

        while (matcher.find()) {
            final String at = matcher.group(0);
            if (at != null) {
                int start = matcher.start();
                int end = matcher.end();
                MyClickableSpan clickableSpan = new MyClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        if (onItemClickListener != null) {
                            if (!TextUtils.isEmpty(txtIdMap.get(at.trim())))
                                onItemClickListener.onUserClick(txtIdMap.get(at.trim()));
                        }
                    }
                };
                spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }


        }

        return spannableString;
    }

    private String matchReplaceTxt(String s) {
        String back = s;
        final String r = "<nickName.*?cosfun>";
        SpannableString spannableString = new SpannableString(back);
        Pattern pattern = Pattern.compile(r);
        Matcher matcher = pattern.matcher(spannableString);
        try {
            while (matcher.find()) {
                final String n = matcher.group(0);
                if (n != null) {
                    String name = n.substring(n.indexOf("@") + 1, n.indexOf("&"));
                    String id = n.substring(n.lastIndexOf("@") + 1, n.indexOf("%"));
                    if (back.indexOf(n) > -1) {
                        back = back.replace(n, "@" + name + " ");
                        txtIdMap.put("@" + name.trim(), id);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return back;
    }
}
